<template>
  <div class="contacts-page">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <!-- 部门 -->
        <el-form-item label="部门">
          <el-input v-model="searchForm.department" placeholder="请输入部门"></el-input>
        </el-form-item>

        <!-- 姓名 -->
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>

        <!-- 创建时间  -->
        <el-form-item label="创建时间">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleResetSearch">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleOpenAddDialog">新增</el-button>
          <el-button type="primary" @click="handleOpenUploadDialog">上传</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表单 -->
    <el-table :data="tableData" style="width: 100%" stripe border>
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column prop="name" label="姓名" width="150" />
      <el-table-column prop="department" label="部门" width="150" />
      <el-table-column prop="post" label="职务" width="150" />
      <el-table-column prop="telephone" label="联系方式" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="updateTime" label="更新时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="text" @click="handleOpenEditDialog(scope.row)">修改</el-button>
          <el-button size="small" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination :total="pagination.total" :page-size.sync="pagination.pageSize"
      :current-page.sync="pagination.currentPage" @pagination-change="handlePaginationChange" />

    <!-- 新增/修改专家弹窗 -->
    <ExpertDialog :visible.sync="dialogVisible" :form="dialogForm" :dialogTitle="dialogMode === 'add' ? '新增专家' : '修改专家'"
      @confirm="handleDialogConfirm" @cancel="handleDialogCancel" />

    <!-- 上传弹窗 -->
    <UploadDialog :visible.sync="uploadDialogVisible" />

  </div>
</template>

<script>
import Pagination from "@/components/Pagination.vue";
import ExpertDialog from "@/components/ExpertDialog.vue";
import UploadDialog from "@/components/UploadDialog.vue";
import { pickerOptions } from "@/common/utils";
import { addExpert, deleteExpert, updateExpert, searchExpertList } from "@/api/contacts.js"
import { DEFAULT_PAGINATION, EXPERT_TABLE_DATA } from "@/common/constants.js";

export default {
  components: {
    Pagination,
    ExpertDialog,
    UploadDialog,
  },

  data() {
    return {
      /**
       * 日期选择器选项
       * @type {Object}
       */
      pickerOptions: pickerOptions,

      /**
       * 弹窗类型
       * @type {String}
       */
      dialogMode: "add",

      /**
       * 表格数据
       */
      tableData: EXPERT_TABLE_DATA,

      /**
       * 弹窗状态
       * @type {Boolean}
       */
      dialogVisible: false,

      /**
       * 上传弹窗状态
       * @type {Boolean}
       */
       uploadDialogVisible: false,

      /**
       * 确认弹窗状态
       * @type {Boolean}
       */
      confirmDialogVisible: false,

      /**
      * 搜索栏数据
      * @type {Object}
      */
      searchForm: {
        department: "",
        name: "",
        dateRange: [],
      },

      /** 
       * 新增专家表单
       * @type {Object}
       */
      dialogForm: {
        name: "",
        post: "",
        department: "",
        telephone: "",
        enable: true,
      },

      /**
       * 分页信息
       * @type {Object}
       */
      pagination: { ...DEFAULT_PAGINATION },
    };
  },

  methods: {
    /**
     * 重置查询
     * @returns {void}
     */
    handleResetSearch() {
      this.searchForm = {
        department: "",
        name: "",
        dateRange: [],
      };
    },

    /**
     * 查询专家列表
     * @returns {void}
     */
    async handleSearch() {
      try {
        this.$loading({ lock: true, text: "正在查询，请稍后..." });

        // 调用查询接口
        const response = await searchExpertList(this.searchForm, this.pagination);

        // 更新表格数据和分页信息
        if (response.success) {
          this.tableData = response.data;
          this.pagination.total = this.tableData.length;            
        } else {
          this.$message.error(response.message || "查询失败");
        }
      } catch (error) {
        console.error("查询失败:", error);
        this.$message.error(error.message || "查询失败");
      } finally {
        this.$loading().close();
      }
    },

    /**
     * 处理分页切换
     * @param {number} pagination.currentPage - 当前页码
     * @param {number} pagination.pageSize - 每页显示的记录数
     * @returns {void}
     */
    handlePaginationChange({ currentPage, pageSize }) {
      this.pagination.currentPage = currentPage;
      this.pagination.pageSize = pageSize;
    },

    /**
     * 打开上传弹窗
     * @returns {void}
     */
    handleOpenUploadDialog() {
      this.uploadDialogVisible = true;
    },

    /**
     * 打开新增弹窗
     * @returns {void}
     */
    handleOpenAddDialog() {
      this.dialogMode = "add";
      this.dialogForm = {
        name: "",
        post: "",
        department: "",
        telephone: "",
        enable: true,
      };
      this.dialogVisible = true;
    },

    /**
     * 打开编辑弹窗
     * @param {Object} row - 当前行数据
     * @returns {void}
     */
    handleOpenEditDialog(row) {
      this.dialogMode = "edit";
      this.dialogForm = { ...row };
      this.dialogVisible = true;
    },

    /**
     * 处理弹窗取消
     * @returns {void}
     */
    handleDialogCancel() {
      this.dialogForm = {
        name: "",
        post: "",
        department: "",
        telephone: "",
        enable: true,
      };
    },

    /**
     * 删除记录
     * @param {Object} row - 当前行数据
     * @returns {void}
     */
    async handleDelete(row) {
      try {
        // 确认删除
        await this.$confirm(`确定删除 ${row.name} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });

        // 调用删除接口
        const response = await deleteExpert(row.id, this.tableData);

        if (response.success) {
          // 更新表格数据
          this.tableData = response.data;
          this.pagination.total = this.tableData.length;

          this.$message.success('删除专家成功');
        } else {
          this.$message.error('删除专家失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '删除专家失败');
        }
      }
    }
    ,

    /**
     * 处理弹窗确认
     * @param {Object} formData - 表单数据
     * @returns {void}
     */
    async handleDialogConfirm(formData) {
      try {
        let response;
        if (this.dialogMode === 'add') {
          // 调用新增接口
          response = await addExpert(formData, this.tableData);
          if (response.success) {
            this.tableData = response.data;
            this.pagination.total = this.tableData.length;

            this.$message.success('新增专家成功');
          } else {
            this.$message.error('新增专家失败');
          }
        } else if (this.dialogMode === 'edit') {
          // 调用修改接口
          response = await updateExpert(formData, this.tableData);
          if (response.success) {
            this.tableData = response.data;
            this.$message.success('修改专家成功');
          } else {
            this.$message.error('修改专家失败');
          }
        }
      } catch (error) {
        this.$message.error(error.message || '操作失败');
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import url('@/assets/scss/form.scss');
</style>
